package com.per.mybootall.shiro;

import com.per.mybootall.filter.OriginFilter;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author 袁
 */ /*
* shiro的配置类
* */
 @Configuration
public class ShiroConfig {
        /*第一步：
        * 创建ShiroFilterFactoryBean
        * */
        @Bean
        public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager){
            ShiroFilterFactoryBean shiroFilterFactoryBean=new ShiroFilterFactoryBean();
            //设置安全管理器
            shiroFilterFactoryBean.setSecurityManager(securityManager);

            /*
            * //添加shiro内置过滤器（shiro内置过滤器，可以实现权限相关的拦截器）
            *
            * 常见的过滤器
            * anon：无需认证（登陆）即可访问
            * authc:必须认证才可以访问
            * user：如果使用了remember me（记住我）的功能可以直接访问
            * perms：该资源必须得到资源权限才可以访问
            * role：该资源必须得到角色权限才可以访问
            * */
            Map<String,String> fileMap= new LinkedHashMap<String, String>();
            ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
            Map<String, Filter> filters = bean.getFilters();
            filters.put("authc",  new OriginFilter());

//            fileMap.put("/testShiro/home","authc");

            // fileMap.put("/templates/user/*","authc");

//            fileMap.put("/testShiro/testMyShiroUser","anon");
//            fileMap.put("/testShiro/login","anon");
//            fileMap.put("/testShiro/tologin","anon");
//            fileMap.put("/testShiro/register","anon");
//            fileMap.put("/testShiro/toregister","anon");
            fileMap.put("/load/*","anon");
            fileMap.put("/testShiro/*","anon");
            fileMap.put("/echo","anon");


            //修改默认的登录页为我们自己的登录页
            shiroFilterFactoryBean.setLoginUrl("/testShiro/tologin");
//            shiroFilterFactoryBean.setUnauthorizedUrl();
            shiroFilterFactoryBean.setFilterChainDefinitionMap(fileMap);
            return shiroFilterFactoryBean;
        }

        /*第二步：
         * 创建DefaultWebSecurityManager
         * */
        @Bean(name = "securityManager")
        public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
            DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
            //需要关联Realm
            securityManager.setRealm(userRealm);
            return securityManager;
        }
        /*第三步：
         * 创建Realm
         * */
    @Bean(name="userRealm")
    public UserRealm getRealm(){
        return new UserRealm();
    }
}
